package leetcode;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q1195.java
 * @Author : WangRuoyu
 * @Date 2023/11/15 20:21
 */


public class Q1195 {
    private volatile int n;
    private volatile int i = 1;
    private volatile Object lock = new Object();

    //    public FizzBuzz(int n) {
    public Q1195(int n) {
        this.n = n;
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        while (i <= n) {
            synchronized (lock) {
                if (i > n) break;
                if (i % 3 == 0 && i % 5 != 0) {
                    printFizz.run();
                    i++;
                }
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        while (i <= n) {
            synchronized (lock) {
                if (i > n) break;
                if (i % 3 != 0 && i % 5 == 0) {
                    printBuzz.run();
                    i++;
                }
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        while (i <= n) {
            synchronized (lock) {
                if (i > n) break;
                if (i % 3 == 0 && i % 5 == 0) {
                    printFizzBuzz.run();
                    i++;
                }
            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
//    public void number(IntConsumer printNumber) throws InterruptedException {
//        while (i <= n) {
//            synchronized (lock) {
//                if (i > n) break;
//                if (i % 3 != 0 && i % 5 != 0) {
//                    printNumber.accept();
//                    i++;
//                }
//            }
//        }
//    }
    public static void main(String[] args) {
        Q1195 sl = new Q1195(0);
    }
}
